<?php

namespace App\Http\Middleware;

use App\Exceptions\AuthorizedException;
use Closure;

class CheckPermission
{
    public function handle($request, Closure $next, $permission = null, $guard = null)
    {
        if (app('auth')->guard($guard)->guest()) {
            throw AuthorizedException::notLoggedIn();
        }

        $user = app('auth')->guard($guard)->user();
        $permissions = is_array($permission)
            ? $permission
            : explode('|', $permission);

        foreach ($permissions as $permission) {
            if (!empty($permission) && $user->can($permission) || $user->can($request->route()->getName())) {
                return $next($request);
            }
        }

        throw AuthorizedException::forPermissions($permissions);
    }
}
